package com.xs.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
//import org.apache.curator.x.discovery.ServiceInstance;
import org.springframework.cloud.zookeeper.serviceregistry.ServiceInstanceRegistration;
import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration;
import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistry;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ServicesController {

	@Autowired
	private DiscoveryClient discoveryClient;
	@Autowired
	private ZookeeperServiceRegistry serviceRegistry;

	@RequestMapping("/getServices")
	public List<String> getServiceUrlList() {
		List<String> serviceList = discoveryClient.getServices();
		return serviceList;

	}

	@RequestMapping("/getServiceDetail/{serviceName}")
	public String getServiceDetail(@PathVariable String serviceName) {

		List<ServiceInstance> serviceList = discoveryClient.getInstances(serviceName);
		List<String> servicesDetail = new ArrayList<String>();
		if (serviceList != null && serviceList.size() > 0) {
			for (ServiceInstance service : serviceList) {
				String serviceD = "serviceName=" + service.getServiceId() + ";uri=" + service.getUri().toString();
				servicesDetail.add(serviceD);
			}

		}

		return servicesDetail.toString();

	}

	@RequestMapping("/registerService/{serviceName}/{port}")
	public void registerService(@PathVariable String serviceName, @PathVariable int port) {
		ZookeeperRegistration registration = ServiceInstanceRegistration.builder().defaultUriSpec().address(serviceName)
				.port(port).name(serviceName).build();
		this.serviceRegistry.register(registration);
		
	}

	
	

}
